let layerIndex;
function showStudentDlg(id) {
    let title="新增学生"
    if(id){
        title="编辑学生"
        $("#formId").css("display","block");
        $.ajax({
            url:"/api/student/"+id,
            method:"GET"
        }).done(result=>{
            console.log(result)
            $.each(result,function(key, value){
                var field = $('#studForm [name="'+ key +'"]');
                if(field.is(':radio')) {
                    field.filter('[value="'+ value +'"]').prop('checked',true);
                }else if (field.is(':checkbox')) {
                    field.prop('checked', value === "yes");
                }else {
                    field.val(value);
                }
            });
        })
    }else{
        $("#studForm")[0].reset();
        $("#formId").css("display","none");
    }
    layerIndex=layer.open({
        type: 1,
        title: title,
        area: ['520px', 'auto'],
        content: $('#studForm')
    });
}
function getSearchCondition() {
    let formData = {};
    $('#queryForm').find('input, select').each(function() {
        let name = $(this).attr('name');
        let value = $(this).val();
        if (name && value) {
            formData[name] = value;
        }
    });
    return formData;
}
layui.use(function (){
    layui.form.on('submit(stud-dlg)',function (data){
        event.preventDefault();
        commitStuBlg();
    })
    const table = layui.table;
    let student = getSearchCondition();
    table.render({
        elem: '#tbStudent',
        url: '/api/student/getbypage',
        method: "POST",
        contentType: 'application/json',
        where: {'data': student},
        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', fixed: 'left', width: 80, title: 'id', sort: true},
            {field: 'name', title: '姓名'},
            {
                field: 'sno',
                title: '学号',
                width: 150,
            },
            {
                field: 'sex', width: 80, title: '性别', sort: true,
                templet: d => d.sex === 1 ? '男' : (d.sex === 2 ? '女' : '未知'),
            },
            {field: 'age', width: 100, title: '年龄', sort: true},
            {fixed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#editTemplate'}
            ]],
            done: function(rs) {
                //console.log(rs)
            }
    });
    table.on('tool(tbStudent)', function(obj) {
        var data = obj.data;
        if(obj.event === 'edit'){
            layer.open({
                title: '编辑 - id:' + data.id,
                type: 1,
                area: ['80%', '80%'],
                content: '<div style="padding: 16px;">自定义表单元素</div>'
            });
        }
    });
});
function search() {
    let student = getSearchCondition();
    console.log("查询条件:", student);
    const table = layui.table;
    table.reloadData('tbStudent', {
        where: {data:student}
    });
    console.log("where condition:"+JSON.stringify(student))
}
function deleteConfirm() {
    const table = layui.table;
    const checkStatus = table.checkStatus('tbStudent');
    console.log(checkStatus);
}
function  commitStuBlg(){
    let id= $("#id").val()
    let formData = $("#studForm").serialize();
    if (id!=null && id!="") {
        $.ajax({
            url: "/api/student/update",
            method: "PUT",
            data: formData
        }).done(result=>{
            console.log(result);
            if(result.id){
                loadStudentList();
                console.log("add success")
                if(layerIndex)
                    layer.close(layerIndex)
            }
        }).fail((jqXHR,textStatus,errorThrown)=>{
            console.error("Request failed: "+textStatus + " - " + errorThrown);
            alert("An error occurred. Please try again.");
        });
    }
    $.ajax({
        url: "/api/student/add",
        method: "POST",
        data: formData
    }).done(result=>{
        console.log(result);
        if(result.id){
            loadStudentList();
            console.log("add success")
            if(layerIndex)
                layer.close(layerIndex)
        }
    }).fail((jqXHR,textStatus,errorThrown)=>{
        console.error("Request failed: "+textStatus + " - " + errorThrown);
        alert("An error occurred. Please try again.");
    });
    $("#btnOK").prop("disabled",true).addClass("layui-btn-disabled");
}
function deleteStudent(id) {
    $.ajax({
        url: "/api/student/delete/" + id,
        method: "DELETE",
    }).done(function (result) {
        console.log(result);
        loadStudentList();
        alert("删除成功！");
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.error("Request failed: " + textStatus + " - " + errorThrown);
        alert("删除失败，请稍后再试。");
    });
}